import os
import configparser
import pymongo
import common.gyblog as log

LOG = log.get_logger()

CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'

# 读取配置
cf = configparser.ConfigParser()
cf.read(os.path.dirname(os.path.abspath('.')) + '/download_javbook/config.ini')
DATA_BASE = cf.get('javbook', 'DATA_BASE')
DB_COL = cf.get('javbook', 'DB_COL')
SERIES = cf.get('javbook', 'SERIES')
YEAR = cf.get('javbook', 'YEAR')

PATH = '\\\\lcnas\\xishu16t2020_1\无遮挡机动车\{}\\{}\\'
PATH_LOCAL = 'D:\无遮挡机动车\{}\\{}\\'

'''
（文件缺失）检查在数据库中，但是不在文件夹中：check_in_database()
（文件放错了）检查不在数据库中，但是在文件夹中： check_error()
'''


def check_error(path, series, year):
    ans = []
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]
    # 查询出全集
    query = {'series': series, 'year': year}
    projection = {'_id': 0, 'num': 1}
    standard_mp4s = list(db_col.find(query, projection))
    # 读出文件夹中的视频
    mp4s = os.listdir(path)
    for mp4 in mp4s:
        if {'num': mp4[:-4]} not in standard_mp4s:
            ans.append(mp4[:-4])
    # print('两个文件夹差异：', len(mp4s) - len(standard_mp4s))
    return ans


def check_in_database(path, series, year):
    ans = []
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]
    # 查询出全集
    query = {'series': series, 'year': year}
    standard_mp4s = list(db_col.find(query))
    # 读出文件夹中的视频
    mp4s = os.listdir(path)
    for standard_mp4 in standard_mp4s:
        if standard_mp4['num'] + '.mp4' not in mp4s:
            ans.append(standard_mp4)
    # print('两个文件夹差异：', len(standard_mp4s) - len(mp4s))
    return ans


def print_ans(path, series, year):
    ans_error = check_error(path, series, year)
    ans_check_temp = check_in_database(path, series, year)
    ans_check = []
    for a in ans_check_temp:
        num_temp = a['num']
        ans_check.append(num_temp)
    intersection = list(set([x for x in ans_error if x in ans_check]))
    print('放错位置的视频有{}个:'.format(len(ans_error)),ans_error)
    print('未下载视频有{}个:'.format(len(ans_check)),ans_check)
    print('交集有{}个\n'.format(len(intersection)))
    for i in intersection:
        print(i)


if __name__ == '__main__':

    for year in ['2023', '2022', '2021', '2020', '2019', '2018', '2017', '2016']:
        print('【{}，{}】'.format(SERIES, year))
        path = PATH.format(SERIES, year)
        path_local = PATH_LOCAL.format(SERIES, year)
        if os.path.exists(path):
            print_ans(path, SERIES, year)
        elif os.path.exists(path_local):
            print_ans(path_local, SERIES, year)
        else:
            print('{},{}，不存在\n'.format(SERIES, year))
